﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Web;
using System.Web.Mvc;
using Data;
using Web.Filters;
using Models;

namespace Web.Controllers
{
    [AuthFilter]
    public class AdminController : BaseController
    {
        //
        // GET: /Admin/

        public ActionResult Index()
        {
            
            
            return View();

        }
        
       
        public ActionResult AddNews()
        {
            
            return View();
        }

        [HttpPost]
        public ActionResult AddNews(News model,string tags, IEnumerable<HttpPostedFileBase> uploadFiles)
        {
            var tagsStrings = tags.Split(',');

            var dbNews = new NewsData();
            var id = dbNews.AddNews(model);

            foreach (string tag in tagsStrings)
            {
                dbNews.AddTagsBind(Convert.ToInt32(tag),id);
            }


            if (uploadFiles != null)
            {
                var path = AppDomain.CurrentDomain.BaseDirectory;
                var imagePath = ConfigurationManager.AppSettings["NewsImageUrl"];
                path = path + imagePath + Convert.ToString(id);

                Directory.CreateDirectory(path);
                foreach (var file in uploadFiles)
                {
                    if (file == null) continue;
                    if (file.ContentType != "image/jpeg" && file.ContentType != "image/png") continue;

                    var filename = Path.GetFileName(file.FileName);
                    if (filename == null) continue;

                    file.SaveAs(Path.Combine(path + "/", filename));

                    var dbImages = new ImagesData();
                    dbImages.SetNewsImageBind(id, file.FileName);
                }
            }

            ViewBag.Message = "The news was successfully added";
            ViewBag.newsID = id;
            return View();
        }

        public ActionResult AllNews(int? page, string orderBy, int? categoryId, string titleSearch, string textSearch)
        {
            
            var dbNews = new NewsData();
            var newsList = dbNews.GetNews(  category: Convert.ToInt32(categoryId),
                                            title: titleSearch,
                                            text: textSearch, 
                                            orderBy:orderBy,
                                            publishDate:0
                                            );
            ViewBag.categoryID = categoryId;
            ViewBag.titleSearch = titleSearch;
            ViewBag.TextSearch = textSearch;

            if (newsList != null)
            {
                var pager = new Pager(newsList.Count, Request.Url.LocalPath, page);
                if (pager.Check() == null)
                {
                    return Redirect("/Admin/AllUsers");
                }
                ViewBag.pager = pager;

                return View(newsList);
            }
            return View();
        }

        [HttpGet]
        public ActionResult UpdateNews(string id)
        {
            if (id == null)
                return Redirect("/Admin");
            var dbNews = new NewsData();
            var newsList = dbNews.GetNews(Convert.ToInt32(id),publishDate:0);

            if(newsList != null)
            {
                ViewBag.selectedTags = newsList[0].TagsList;
                return View(newsList[0]);
            }
            
            return Redirect("/Admin");
        }

        [HttpPost]
        public ActionResult UpdateNews(News model, IEnumerable<HttpPostedFileBase> uploadFiles, string imagesToDelete, string tags)
        {
            if (ModelState.IsValid)
            {
                var dbNews = new NewsData();
                if (!string.IsNullOrEmpty(imagesToDelete))
                {
                    var imageTodeleteList = imagesToDelete.Split(',');
                    var dbImages = new ImagesData();
                    model.Images = dbImages.GetNewsImagesUrl(model.Id);
                    for(int i = 0; i < imageTodeleteList.Length;i++)
                    {
                        dbImages.DeleteNewsImage(Convert.ToInt32(imageTodeleteList[i]));
                        for(int j = 0; j < model.Images.Count;j++)
                        {
                            if(model.Images[j].Id == Convert.ToInt32(imageTodeleteList[i]))
                            System.IO.File.Delete(AppDomain.CurrentDomain.BaseDirectory + model.Images[j].Url);
                        }
                    }
                }
                dbNews.DeleteTagsBind(model.Id);
                if (!string.IsNullOrEmpty(tags))
                {
                    var tagsStrings = tags.Split(',');

                    foreach (string tag in tagsStrings)
                    {
                        dbNews.AddTagsBind(Convert.ToInt32(tag), model.Id);
                    }
                }
               
                if (uploadFiles != null)
                {
                    var path = AppDomain.CurrentDomain.BaseDirectory;
                    var imagePath = ConfigurationManager.AppSettings["NewsImageUrl"];
                    path = path + imagePath + Convert.ToString(model.Id);

                    Directory.CreateDirectory(path);
                    foreach (var file in uploadFiles)
                    {
                        if (file == null) continue;
                        if (file.ContentType != "image/jpeg" && file.ContentType != "image/png") continue;

                        var filename = Path.GetFileName(file.FileName);
                        if (filename == null) continue;

                        file.SaveAs(Path.Combine(path + "/", filename));

                        var dbImages = new ImagesData();
                        dbImages.SetNewsImageBind(model.Id, file.FileName);
                    }
                }

                model.UpdateDate = DateTime.Now;
                dbNews.UpdateNews(model);

                ViewBag.Message = "The news edited successfully";

                return View();
            }
            ViewBag.Message = "Error when editing";
            return View(model);
        }
        [AdminFilter]
        public ActionResult DeleteNews(string id)
        {
            if (id == null)
            {
                return Redirect("/Admin");
            }

            var dbNews = new NewsData();
            dbNews.DeleteNews(Convert.ToInt32(id));

            ViewBag.Message = "The news was successfully deleted";

            return View();
        }

        public ActionResult PublishNews(string id)
        {
            if (id == null)
            {
                return Redirect("/Admin");
            }

            var dbNews = new NewsData();
            dbNews.PublishNews(Convert.ToInt32(id));
            
            return View("newsPublished");
            
        }


        public ActionResult AllUsers(int? page, string orderBy)
        {
            var dbUsers = new UsersData();

            var usersList = dbUsers.GetUsers(orderBy:orderBy);
            if(usersList != null)
            {
                var pager = new Pager(usersList.Count, Request.Url.LocalPath, page);
                if (pager.Check() == null)
                {
                    return Redirect("/Admin/AllUsers");
                }
                ViewBag.pager = pager;
                return View(usersList);
            }
            
            return Redirect("/Admin");
        }

        [AdminFilter]
        public ActionResult AddUser()
        {
            return View();
        }

        [AdminFilter]
        [HttpPost]
        public ActionResult AddUser(Users model, IEnumerable<HttpPostedFileBase> fileUpload)
        {
            if (ModelState.IsValid)
            {
                var dbUsers = new UsersData();
                var id = dbUsers.AddUser(model);
                ViewBag.Message = "User added successfully";

                if (fileUpload != null)
                {
                    var path = AppDomain.CurrentDomain.BaseDirectory;
                    var imagePath = ConfigurationManager.AppSettings["UsersImageUrl"];
                    path = path + imagePath + Convert.ToString(id);
                    
                    Directory.CreateDirectory(path);
                    foreach (var file in fileUpload)
                    {
                        if (file == null) continue;
                        if (file.ContentType != "image/jpeg" && file.ContentType != "image/png") continue;

                        var filename = Path.GetFileName(file.FileName);
                        if (filename == null) continue;

                        file.SaveAs(Path.Combine(path + "/", filename));

                        var dbImages = new ImagesData();
                        dbImages.SetUserImageBind(id, file.FileName);
                    }
                }

                return View();
            }

            return View(model);
        }

        [AdminFilter]
        [HttpGet]
        public ActionResult UpdateUser(int id)
        {
            if (id == 0)
            {
                return Redirect("/Admin");
            }

            var dbUsers = new UsersData();
            var usersList = dbUsers.GetUsers(id);

            if(usersList != null)
            {
                return View(usersList[0]);
            }
            
            return View();
        }

        [AdminFilter]
        [HttpPost]
        public ActionResult UpdateUser(Users model , IEnumerable<HttpPostedFileBase> uploadFile)
        {
            if (ModelState.IsValid)
            {
                if(uploadFile != null)
                {
                    var path = AppDomain.CurrentDomain.BaseDirectory;
                    var imagePath = ConfigurationManager.AppSettings["UsersImageUrl"];
                    path = path + imagePath + Convert.ToString(model.Id);

                    if(string.IsNullOrEmpty(model.Image)) Directory.CreateDirectory(path);
                    else System.IO.File.Delete(AppDomain.CurrentDomain.BaseDirectory+model.Image);

                    foreach (var file in uploadFile)
                    {
                        if (file == null) continue;
                        if (file.ContentType != "image/jpeg" && file.ContentType != "image/png") continue;

                        var filename = Path.GetFileName(file.FileName);
                        if (filename == null) continue;

                        file.SaveAs(Path.Combine(path + "/", filename));
                        
                        var dbImages = new ImagesData();
                        dbImages.SetUserImageBind(model.Id, file.FileName);
                       
                    }
                }
                var dbUsers = new UsersData();
                dbUsers.UpdateUser(model);

                ViewBag.Message = "User updated successfully";
                return View();
            }
            return View(model);
        }

        [AdminFilter]
        [HttpGet]
        public ActionResult DeleteUser(string id)
        {
            if (id != null)
            {
                var dbUsers = new UsersData();
                dbUsers.DeleteUser(Convert.ToInt32(id));
                ViewBag.Message = "User have beed deleted";
            }
            else
                Redirect("/admin/allUsers");

            return View();
        }

        public ActionResult Tags(int? page)
        {
            var dbTags = new TagsData();
            var tagsList = dbTags.GetTags();
            if (tagsList != null)
            {
                var pager = new Pager(tagsList.Count, Request.Url.LocalPath, page);

                if (pager.Check() == null)
                    return Redirect("/Admin");

                ViewBag.pager = pager;
            }
            return View(tagsList);
        }

        public ActionResult AddTag()
        {

            return View();
        }

        [HttpPost]
        public ActionResult AddTag(Tag tag)
        {
            if(ModelState.IsValid)
            {
                var dbTags = new TagsData();
                dbTags.AddTag(tag.Name);
                
                ViewBag.Message = "Tag added successfully";
                return View();
            }
            return View(tag);
        }

        [HttpGet]
        public ActionResult UpdateTag(string id)
        {
            if (id == null)
                return Redirect("/Admin/Tags");

            var dbTags = new TagsData();
            var tagsList = dbTags.GetTags(Convert.ToInt32(id));
            if(tagsList.Count > 0)
            {
                return View(tagsList[0]);
            }

            return Redirect("/Admin/Tags");
        }
        
        [HttpPost]
        public ActionResult UpdateTag(Tag tag)
        {
            if(ModelState.IsValid)
            {
                var dbTags = new TagsData();
                dbTags.UpdateTag(tag);
                ViewBag.Message = "Tag updated successfully";

                return View();
            }
            return View(tag);
        }

        [AdminFilter]
        [HttpGet]
        public ActionResult DeleteTag(int? id)
        {
            if (id == null)
                return Redirect("/Admin/Tags");
            var dbTags = new TagsData();
            var dbNews = new NewsData();
            var tag = dbTags.GetTags(Convert.ToInt32(id));
            if(tag != null)
            {
                if (dbNews.GetNews(tagName: tag[0].Name) != null)
                {
                    ViewBag.Message = "There some news binding to this tag";
                    return View();
                }
           
                dbTags.DeleteTag(Convert.ToInt32(id) );
            }
            return View();
        }

        public ActionResult AddCategory()
        {
            return View();
        }

        [HttpPost]
        public ActionResult AddCategory(Category category)
        {
            if(ModelState.IsValid)
            {
                var dbCategory = new CategoryData();
                dbCategory.AddCategory(category);
                ViewBag.Message = "Category added successfully";
                return View();
            }
            return View(category);
        }

        [AdminFilter]
        [HttpGet]
        public ActionResult DeleteCategory(int? id)
        {
            if (id == null)
                return Redirect("/admin/Categories");

            var dbCategory = new CategoryData();
            if (dbCategory.GetCategories((int)id) == null)
            {
                dbCategory.DeleteCategory((int)id );
                return View();
            }
            else
            {
                ViewBag.Message = "category not empty!";
            }

            return View();
        }

        [HttpGet]
        public ActionResult UpdateCategory(int? id)
        {
            if (id == null)
                return Redirect("/Admin/Categories");

            var dbCategory = new CategoryData();
            var categoryList = dbCategory.GetCategories((int) id);
            if(categoryList.Count > 0)
            {
                return View(categoryList[0]);
            }
            return Redirect("/Admin/Categories");
        }

        [HttpPost]
        public ActionResult UpdateCategory(Category category)
        {
            if(ModelState.IsValid)
            {
                var dbCategory = new CategoryData();
                dbCategory.UpdateCategory(category);
                ViewBag.Message = "Category updated successfully";
                return View();
            }
            return View(category);
        }

        [HttpGet]
        public ActionResult Categories(int? page , string orderBy)
        {
            var dbCategory = new CategoryData();
            var categoryList = dbCategory.GetCategories(orderBy: orderBy);

            if (categoryList != null)
            {
                var pager = new Pager(categoryList.Count, Request.Url.LocalPath, page);
                if (pager.Check() == null)
                {
                    pager.CurrentPage = 1;
                }
                
                ViewBag.pager = pager;

                return View(categoryList);
            }
            return View();
        }

        public ActionResult AllImages(int?page )
        {
            var dbImages = new ImagesData();
            var imagesInNewsList = new List<ImageInNews>();
            imagesInNewsList = dbImages.GetNewsImages();
            var userImagesList = new List<UserImage>();
            userImagesList = dbImages.GetUserImages();

            var pager = new Pager(imagesInNewsList.Count + userImagesList.Count, Request.Url.LocalPath, page);

            if (pager.Check() == null) pager.CurrentPage = 1;

            ViewBag.pager = pager;
            ViewBag.userImagesList = userImagesList;
            ViewBag.imagesInNewsList = imagesInNewsList;

            return View();
                
        }

        public ActionResult DeleteNewsImage(int id)
        {
            var dbImages = new ImagesData();
            var imageList = dbImages.GetNewsImages(id:id);
            if(imageList != null)
            {
                var image = imageList[0];
                System.IO.File.Delete(AppDomain.CurrentDomain.BaseDirectory+"/Content/news_images/"+image.NewsId+"/"+image.Name);
                dbImages.DeleteNewsImage(image.Id);
                return View("DeleteImage",image);
            }
            ViewBag.Message = "Image not found";
            return View("DeleteImage");
            
        }
        public ActionResult DeleteUserImage(int id)
        {
            var dbImages = new ImagesData();
            var imageList = dbImages.GetUserImages(id: id);
            if (imageList != null)
            {
                var image = imageList[0];
                System.IO.File.Delete(AppDomain.CurrentDomain.BaseDirectory + "/Content/users_images/" + image.UserId + "/" + image.Name);
                dbImages.DeleteNewsImage(image.Id);
                return View("DeleteUserImage", image);
            }
            ViewBag.Message = "Image not found";
            return View("DeleteUserImage");

        }

        public ActionResult DeleteComment(int id)
        {
            var dbComment = new CommentsData();
            var commentsList = dbComment.GetComments(id:id);
            if(commentsList != null)
            {
                dbComment.DeleteComment(id);
                return Redirect("/Home/Index/" + commentsList[0].NewsId);
            }
            return Redirect("/Home");
        }
        
        [HttpGet]
        public ActionResult EditComment(int id)
        {
            var dbComment = new CommentsData();
            var commentsList = dbComment.GetComments(id: id);
            if(commentsList != null)
            {
                return View(commentsList[0]);
            }
            return Redirect("/");
        }

        [HttpPost]
        public ActionResult EditComment(Comment model)
        {
            if(ModelState.IsValid)
            {
                var dbComment = new CommentsData();
                dbComment.EditComment(model);
                ViewBag.Message = "Edited successfully";
                return View(model);
            }
            return View(model);
        }

        [UserAuth]
        public ActionResult AddImageToNews(int? id = null)
        {
            if (id == null)
            {
                var dbNews = new NewsData();
                var newsList = dbNews.GetNews(publishDate: 0);
                return View(newsList);
            }

            ViewBag.newsID = id;
            return View();
        }

        [UserAuth]
        [HttpPost]
        public ActionResult AddImageToNews(int? id, IEnumerable<HttpPostedFileBase> fileUpload)
        {
            if (fileUpload != null)
            {
                var path = AppDomain.CurrentDomain.BaseDirectory;
                path = Path.Combine(path, "Content/news_images/" + id);
                Directory.CreateDirectory(path);
                foreach (var file in fileUpload)
                {
                    if (file == null) continue;
                    if (file.ContentType != "image/jpeg" && file.ContentType != "image/png") continue;

                    var filename = Path.GetFileName(file.FileName);
                    if (filename == null) continue;

                    file.SaveAs(Path.Combine(path + "/", filename));
                    var dbImages = new ImagesData();
                    dbImages.SetNewsImageBind(Convert.ToInt32(id), file.FileName);
                }
                ViewBag.Message = "Files successfully loaded!";
            }
            return View();
        }
    }
}
